package routers

import (
	v1 "gin-example/routers/api/v1"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"

	"gin-example/pkg/setting"
)

func InitRouter() *gin.Engine {
	r := gin.New()

	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "GET", "POST", "HEAD", "OPTIONS", "DELETE"},
		AllowHeaders:     []string{"Origin", "Authorization", "Content-Type", "x-token"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowOriginFunc: func(origin string) bool {
			return true
		},
		MaxAge: 12 * time.Hour,
	}))

	r.Use(gin.Logger())

	r.Use(gin.Recovery())

	r.StaticFS("/static", http.Dir("./web/static"))
	r.StaticFS("/assets", http.Dir("./assets"))
	gin.SetMode(setting.RunMode)

	r.LoadHTMLGlob("./web/index.html")
	r.Handle("GET", "/", func(context *gin.Context) {
		// 返回HTML文件，响应状态码200，html文件名为index.html，模板参数为nil
		context.HTML(http.StatusOK, "index.html", nil)
	})

	apiv1 := r.Group("/api/v1")
	{
		apiv1.GET("/userinfo", v1.GetUserInfo)
		apiv1.POST("/login", v1.Login)
		apiv1.POST("/upPic", v1.UploadPic)

		apiv1.GET("/member", v1.GetAllMembers)
		apiv1.POST("/member", v1.AddMember)
		apiv1.PUT("/member/:id", v1.UpdateMember)
		apiv1.DELETE("/member/:id", v1.DeleteMember)

		apiv1.GET("/course", v1.GetAllCourses)
		apiv1.POST("/course", v1.AddCourse)
		apiv1.PUT("/course/:id", v1.UpdateCourse)
		apiv1.DELETE("/course/:id", v1.DeleteCourse)

		apiv1.GET("/direction", v1.GetAllDirections)
		apiv1.POST("/direction", v1.AddDirection)
		apiv1.PUT("/direction/:id", v1.UpdateDirection)
		apiv1.DELETE("/direction/:id", v1.DeleteDirection)

		apiv1.GET("/monograph", v1.GetAllMonographs)
		apiv1.POST("/monograph", v1.AddMonograph)
		apiv1.PUT("/monograph/:id", v1.UpdateMonograph)
		apiv1.DELETE("/monograph/:id", v1.DeleteMonograph)

		apiv1.GET("/patent", v1.GetAllPatents)
		apiv1.POST("/patent", v1.AddPatent)
		apiv1.PUT("/patent/:id", v1.UpdatePatent)
		apiv1.DELETE("/patent/:id", v1.DeletePatent)

		apiv1.GET("/project", v1.GetAllProjects)
		apiv1.POST("/project", v1.AddProject)
		apiv1.PUT("/project/:id", v1.UpdateProject)
		apiv1.DELETE("/project/:id", v1.DeleteProject)

		apiv1.GET("/paper", v1.GetAllPapers)
		apiv1.POST("/paper", v1.AddPaper)
		apiv1.PUT("/paper/:id", v1.UpdatePaper)
		apiv1.DELETE("/paper/:id", v1.DeletePaper)

		apiv1.GET("/service", v1.GetAllServices)
		apiv1.POST("/service", v1.AddService)
		apiv1.PUT("/service/:id", v1.UpdateService)
		apiv1.DELETE("/service/:id", v1.DeleteService)

		apiv1.GET("/content", v1.GetAllContents)
		apiv1.GET("/content/page", v1.GetContentsByOffset)
		apiv1.POST("/content", v1.AddContent)
		apiv1.PUT("/content/:id", v1.UpdateContent)
		apiv1.DELETE("/content/:id", v1.DeleteContent)

		apiv1.GET("/image", v1.GetAllImages)
		apiv1.POST("/image", v1.AddImage)
		apiv1.PUT("/image/:id", v1.UpdateImage)
		apiv1.DELETE("/image/:id", v1.DeleteImage)
	}
	return r
}